<template>
  <!-- 头部导航栏 -->
  <div class="header-nav">
    <!-- 导航栏图标 -->
    <i
      class="iconfont icon-a-gonggongqichekechegongjiaoche"
      style="font-size: 30px"
    ></i>
    <div class="title">光谷智慧交通</div>
    <span class="user-type">({{ systemType }})</span>
    <!-- 主菜单 -->
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      :ellipsis="false"
      style="width: 1200px"
    >
      <el-menu-item index="1" @click="showTrafficInformation"
        >实时路况</el-menu-item
      >
      <el-menu-item index="2" @click="checkNotice">查看公告</el-menu-item>
      <el-menu-item index="3" @click="openRoadCondition">报告路况</el-menu-item>
      <el-sub-menu index="4"  v-if = "userType == 'admin' || userType == 'traffic'">
        <template #title>视频监控</template>
        <el-menu-item index="4-1" @click="startVideoMonitoring">查看监控</el-menu-item>
        <el-menu-item index="4-2" @click="stopVideoMonitoring">停止查看</el-menu-item>
      </el-sub-menu>
      <el-menu-item index="5" @click="addEvent($map)" v-if = "userType == 'admin' || userType == 'traffic'">事件添加</el-menu-item>
      <el-sub-menu index="6" v-if = "userType == 'admin' || userType == 'traffic'">
        <template #title>事件查询</template>
        <el-menu-item index="2-2" @click="handleQuery">拉框查询</el-menu-item>
        <el-menu-item index="2-3" @click="cancelQuery">取消查询</el-menu-item>
      </el-sub-menu v-if = "userType == 'admin' || userType == 'traffic'">
      <el-menu-item index="7" @click="updateEvent($map)" v-if = "userType == 'admin' || userType == 'traffic'">事件更新</el-menu-item>
      <el-sub-menu index="8" v-if = "userType == 'admin' || userType == 'traffic'">
        <template #title>发布公告</template>
        <el-menu-item index="3-1" @click="addNotice($map)"
          >缓冲分析</el-menu-item
        >
        <el-menu-item index="3-2" @click="removeBuffer($map)"
          >取消画笔</el-menu-item
        >
        <el-menu-item index="3-3" @click="manageNotice" v-if = "userType == 'admin' || userType == 'traffic'">公告管理</el-menu-item>
      </el-sub-menu>
      <el-menu-item index="9" @click="openTraffic" v-if = "userType == 'admin' || userType == 'traffic'">路况信息</el-menu-item>
      <el-menu-item
      v-if = "userType == 'admin'"
        index="10"
        @click="$headerNavStore.changeDialogVisible(true)"
        >用户信息</el-menu-item
      >
    </el-menu>
    <!-- 右侧事件类型选择器 -->
    <div class="nav-right" style="margin-left: auto">
      <el-select v-model="eventTypeVal" placeholder="请选择事件类型" size="large" style="width: 240px" @change="handleSearch">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="default" @click="handleClear" style="margin-left: 10px"
        >清空</el-button
      >
    </div>
    <!-- 用户下拉菜单 -->
    <el-dropdown style="margin-right: 20px">
      <span class="el-dropdown-link">
        {{ $store.currentUser.username }}
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="handleChangePassword">修改密码</el-dropdown-item>
          <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>

  <!-- 视频监控弹窗 -->
  <el-dialog v-model="videoDialogVisible" title="视频监控" width="30%" :before-close="handleCloseVideoDialog">
    <div v-if="selectedCamera">
      <p><strong>编号:</strong> {{ selectedCamera.CameraNumber }}</p>
      <p><strong>位置:</strong> {{ selectedCamera.location }}</p>
      <video :src="selectedCamera.url" width="100%" autoplay muted loop playsinline></video>
    </div>
    <div v-else>
      <p>未选择摄像头</p>
    </div>
  </el-dialog>
  <trafficforrode :showTrafficLayer="showTrafficLayer" />
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, markRaw } from 'vue'
const { proxy } = getCurrentInstance()
import { Query } from '../mapgis-api/Query.js'
import { setMarkerStyle } from '../ol-api/setMarkerStyle.js'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  useLoginStore,
  useNoticeStore,
  useRoadConditoinStore,
  useHeaderNavStore,
  useTrafficStore,
} from '../stores/counter.js'
import { storeToRefs } from 'pinia'
import { useMapStore } from '../stores/map.js'
import { createDraw } from '@/ol-api/createDraw'
import { setPopup } from '@/ol-api/popup'
import imgUrl from '../imgs/placeholder.png'
import imgUrl2 from '../imgs/weizhi.png'
//拉框查询
import { pullboxQuery } from '../hooks/pullboxQuery.js'
import { stateNumToWord } from '../hooks/usehooks.js'
import axios from 'axios'
import Trafficforrode from './TrafficForRod.vue'
//headerNavHook方法导入
import {
  addEvent,
  updateEvent,
  removeBuffer,
  addNotice,
} from '@/components/headerNavHook/useDrawHook.js'

let $map = null
let $docLayer = null
const $store = useLoginStore()
const $mapStore = useMapStore()
const $router = useRouter()
const { togglePublicNoticeVisible, toggleWatchNoticeVisible } =
  useTrafficStore()
const { showRoadCondition, showTraffic } = useRoadConditoinStore()
const { roadConditionLocation } = storeToRefs(useRoadConditoinStore())
const $headerNavStore = useHeaderNavStore()
const trafficStore = useTrafficStore()
const { toggleAddPopupVisible, toggleUpdatePopupVisible } = useTrafficStore()

const activeIndex = ref('0')
const eventTypeVal = ref('')
const videoDialogVisible = ref(false)
const selectedCamera = ref(null)


const user = JSON.parse( localStorage.getItem('currentUser'))
 const userType = user.type
 console.log(userType)
 const getSystemType = ()=>{
   if(userType == 'admin'){
     return '超管系统'
   }else if(userType == 'traffic'){
     return '交通系统'
   }else{
     return '普通用户'
   }
 }
 const systemType = getSystemType()


//事件类型选项
const options = [
  { value: '碰撞', label: '碰撞' },
  { value: '刮擦', label: '刮擦' },
  { value: '失火', label: '失火' },
  { value: '翻车', label: '翻车' },
  { value: '碾压', label: '碾压' },
  { value: '其他', label: '其他' },
]

let map = null
let source = null
let layer = null
let draw = null
let service = null

onMounted(() => {
  draw = createDraw({
    type: 'Box',
    source,
  })
})
/* 定义显示路况与否 */
const showTrafficLayer = ref(false)
const showTrafficInformation = () => {
  showTrafficLayer.value = !showTrafficLayer.value
}
//唤醒拉框画笔
const handleQuery = () => {
  if ($mapStore.find_source) {
    $mapStore.find_source.clear()
  }
  if (source) {
    source.clear()
  }
  $map.addInteraction(draw)
  service = {
    name: 'xm',
    layerId: 2,
  }
  draw.on('drawend', (evt) => {
    map.removeInteraction(draw)
    let geometry = evt.feature.getGeometry()
    pullboxQuery(geometry, service.name, service.layerId, querySuccess)
  })
  $mapStore.find_source = new ol.source.Vector({})
  $mapStore.find_layer = new ol.layer.Vector({
    source: $mapStore.find_source,
    style: setMarkerStyle(imgUrl),
    zIndex: 10000,
  })
  map.addLayer($mapStore.find_layer)
}
//拉框查询成功回调
const querySuccess = (data) => {
  console.log(data.SFEleArray)
  stateNumToWord(data.SFEleArray)
  console.log(data.SFEleArray)
  $mapStore.setTableData(data.SFEleArray) //存储事件信息
  if ($mapStore.find_source) {
    $mapStore.find_source.clear()
  }
  if ($mapStore.high_source) {
    $mapStore.high_source.clear()
  }
  var format = new Zondy.Format.PolygonJSON()
  var features = format.read(data)
  $mapStore.find_source.addFeatures(features)
  //打开查询结果表格
  $mapStore.setEventTableShow(true)
}
//取消拉框查询
const cancelQuery = () => {
  map.removeInteraction(draw)
  if ($mapStore.find_source) {
    $mapStore.find_source.clear()
  }
  if (source) {
    source.clear()
  }
  if ($mapStore.heatMapSource) {
    $mapStore.heatMapSource.clear()
  }
  $mapStore.setTableData([]) //清空事件信息
}

//报告路况弹窗
const openRoadCondition = () => {
  //提示
  if (confirm('请选择路况信息的位置')) {
    let draw = createDraw({
      type: 'Point',
      source,
    })
    map.addInteraction(draw)
    draw.on('drawend', (evt) => {
      roadConditionLocation.value = null
      map.removeInteraction(draw)
      let geometry = evt.feature.getGeometry().flatCoordinates
      // console.log(geometry)
      map.removeInteraction(draw)
      roadConditionLocation.value = geometry.map((item) => item.toFixed(3))
      console.log(roadConditionLocation.value)
      showRoadCondition()
    })
  } else {
    return
  }
}
const openTraffic = () => {
  showTraffic()
}
//查询事件(地图显示事件)
const handleSearch = () => {
  $mapStore.setTableData([])
  const map = proxy.$map
  console.log(map)
  // 清除之前的图层和数据源
  if ($mapStore.high_source) {
    $mapStore.high_source.clear()
  }
  if ($mapStore.find_source) {
    $mapStore.find_source.clear()
  }
  if ($mapStore.heatMapSource) {
    $mapStore.heatMapSource.clear()
  }
  if (source) {
    source.clear()
  }

  map.removeInteraction(draw)

  const service = {
    name: 'xm',
    layerId: 2,
  }
  $mapStore.high_source = new ol.source.Vector({})

  $mapStore.high_layer = new ol.layer.Vector({
    source: $mapStore.high_source,
    style: setMarkerStyle(imgUrl2),
    zIndex: 10000,
  })

  map.addLayer($mapStore.high_layer)
  let name = eventTypeVal.value
  let where = {
    key: '事件类型',
    value: name,
  }
  Query.queryByAttr({
    where,
    service,
    success: (features) => {
      $mapStore.high_source.addFeatures(features)
      console.log(features)
    },
  })
}
//清空事件
const handleClear = () => {
  if ($mapStore.high_source) {
    $mapStore.high_source.clear()
  }
  eventTypeVal.value = ''
}
//打开密码修改弹窗
const handleChangePassword = () => {
  $mapStore.setPasswordShow(true)
}
//退出登录
const handleLogout = async () => {
  // 下线操作
  await axios.post('/api/logout', {
    "username": $store.currentUser.username,
    "type": $store.currentUser.type
  })
  localStorage.removeItem('token')
  localStorage.removeItem('currentUser')
  $router.push('/')
}

//查看公告
const checkNotice = () => {
  if (trafficStore.addPopupVisible) {
    toggleAddPopupVisible()
  } else if (trafficStore.updatePopupVisible) {
    toggleUpdatePopupVisible()
  } else if (!trafficStore.watchNoticeVisible) {
    toggleWatchNoticeVisible()
  } else if (trafficStore.publicNoticeVisible) {
    togglePublicNoticeVisible()
  }
}
//公告管理
const manageNotice = () => {
  trafficStore.manageNoticeVisible = true
}
// 视频监控相关功能
const startVideoMonitoring = () => {
  $map.on('click', handleMapClick)
}

const stopVideoMonitoring = () => {
  $map.un('click', handleMapClick)
  videoDialogVisible.value = false
  selectedCamera.value = null
}

const handleMapClick = (evt) => {
  const clickedCoord = evt.coordinate

  const pointObj = new Zondy.Object.Point2D(clickedCoord[0], clickedCoord[1])
  pointObj.nearDis = 0.001

  const queryStruct = new Zondy.Service.QueryFeatureStruct()
  queryStruct.IncludeGeometry = true
  queryStruct.IncludeAttribute = true
  queryStruct.IncludeWebGraphic = false

  const rule = new Zondy.Service.QueryFeatureRule({
    EnableDisplayCondition: false,
    MustInside: false,
    CompareRectOnly: false,
    Intersect: true,
  })

  const queryParam = new Zondy.Service.QueryParameter({
    geometry: pointObj,
    resultFormat: 'json',
    struct: queryStruct,
    rule: rule,
  })

  queryParam.pageIndex = 0
  queryParam.recordNumber = 10

  const queryService = new Zondy.Service.QueryDocFeature(
    queryParam,
    'xm',
    3,
    {}
  )

  queryService.query(handleQueryResult)
}

const handleQueryResult = (data) => {
  const format = new Zondy.Format.PolygonJSON()
  const features = format.read(data)

  if (features && features.length > 0) {
    const feature = features[0]
    const properties = feature.getProperties()
    // console.log(properties.values_.位置)

    // 在这里添加一些防护检查
    selectedCamera.value = {
      CameraNumber: properties.values_.编号
        ? properties.values_.编号.replace(/^"|"$/g, '')
        : 'N/A',
      location: properties.values_.位置 ? properties.values_.位置 : 'Unknown',
      url: properties.values_.URL ? properties.values_.URL : '#',
    }

    videoDialogVisible.value = true
  } else {
    ElMessage.warning('未找到该位置的摄像头')
  }
}
// 关闭视频监控弹窗
const handleCloseVideoDialog = (done) => {
  selectedCamera.value = null
  done()
}
onMounted(() => {
  $map = proxy.$map
  map = $map
  $docLayer = proxy.$docLayer
  //初始化popup
  setPopup(null, $map)
})
</script>

<style scoped>
.user-type{
  width: 80px;
  font-size: 14px;
  color: #999;

}

.header-nav {
  width: 100%;
  display: flex;
  align-items: center;
  font-weight: bold;
  gap: 10px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  box-shadow: 0 0.3px 0.7px rgba(0, 0, 0, 0.126),
    0 0.9px 1.7px rgba(0, 0, 0, 0.179), 0 1.8px 3.5px rgba(0, 0, 0, 0.224),
    0 3.7px 7.3px rgba(0, 0, 0, 0.277), 0 10px 20px rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(20px);
  transition: 0.5s ease;
}

:deep(.el-menu) {
  background-color: transparent;
}

.header-nav:hover {
  box-shadow: 0 0.7px 1px rgba(0, 0, 0, 0.157),
    0 1.7px 2.6px rgba(0, 0, 0, 0.224), 0 3.5px 5.3px rgba(0, 0, 0, 0.28),
    0 7.3px 11px rgba(0, 0, 0, 0.346), 0 20px 30px rgba(0, 0, 0, 0.5);
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  width: 130px;
  display: flex;
  height: 100%;
}

@media (max-width: 1200px) {
  .title {
    font-size: 16px;
  }

  .el-menu-item {
    font-size: 14px;
  }
}

@media (max-width: 992px) {
  .title {
    font-size: 14px;
  }

  .el-menu-item {
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .title {
    font-size: 12px;
  }

  .el-menu-item {
    font-size: 10px;
  }
}

@media (max-width: 576px) {
  .title {
    font-size: 10px;
  }

  .el-menu-item {
    font-size: 8px;
  }
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.el-dropdown:hover {
  cursor: pointer;
  color: #409eff;
}
:deep(.el-dropdown-menu__item:hover) {
  background-color: transparent; /* 移除背景颜色 */
  color: #409eff; /* 设置文本颜色为蓝色 */
  border: none; /* 移除边框 */
}
</style>
